package com.hk.mini;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class MiniDecoder extends ByteToMessageDecoder {

    Logger logger = LoggerFactory.getLogger(ByteToMessageDecoder.class);

    /**
     * 协议开始头+后续长度
     * 2+2
     */
    public final int BASE_LENGTH = 2+2;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {

//        logger.debug("开始解码");

        if (buffer.readableBytes() >=BASE_LENGTH){

            //记录包头开始的index
            int beginReader;

            while (true){

                //获取包头开始的index
                beginReader = buffer.readerIndex();

                //标记包头开始的index
                buffer.markReaderIndex();

                //读到了协议开始标志，结束while循环
                if (buffer.readShort() == MiniHead.HEAD_DATA){
                    break;
                }

                //未读到包头，略过一个字节
                //每次略过一个字节，直到读到包头信息的开始标记
                buffer.resetReaderIndex();
                buffer.readByte();

                //略过一个字节后 后续长度小于最小长度，结束，等待后面数据到达
                if (buffer.readableBytes()<BASE_LENGTH){
                    return;
                }

            }

            //消息的长度  可能要*2
            int length = buffer.readShort();

            //判断请求数据是否到齐
            if (buffer.readableBytes()<length){
                //未到齐还原指针
                buffer.readerIndex(beginReader);
                return;
            }

            //到齐开始读取数据
            byte[] data = new byte[length];

            buffer.readBytes(data);

            buffer.clear();
            MiniProtocol protocol = new MiniProtocol(length,data);

            out.add(protocol.toString());
        }
    }
}
